package wsdc.app.main.v2;// DynamicSniMapper.java
import io.netty.handler.ssl.SslContext;
import io.netty.util.Mapping;

import wsdc.app.main.SpringContext;
import wsdc.app.main.v1.CertApi;

import javax.net.ssl.SSLException;

/**
 * 动态SNI映射器，根据SNI主机名映射到相应的SSL上下文
 */
public class DynamicSniMapper implements Mapping<String, SslContext> {
    
    private final PKCSCertificateManager certificateManager;
    
    public DynamicSniMapper(PKCSCertificateManager certificateManager) {
        this.certificateManager = certificateManager;
    }

    CertApi certApi;
    {
        SpringContext.register(c -> {
            certApi = c.getBean(CertApi.class);
        });
    }
    
    @Override
    public SslContext map(String hostname) {
        // 如果没有提供主机名，使用默认值
        if (hostname == null || hostname.isEmpty()) {
            hostname = "default";
        }
        
        try {
            // 尝试加载对应主机名的证书
            return certificateManager.loadSslContext(hostname);
        } catch (SSLException e) {
            e.printStackTrace();
            System.err.println("Failed to load certificate for " + hostname + ": " + e.getMessage());
            try {
                // 回退到默认证书
                return certificateManager.getDefaultSslContext();
            } catch (SSLException defaultException) {
                System.err.println("Failed to load default certificate: " + defaultException.getMessage());
                return null;
            }
        }
    }
}
